package com.platform.security.component;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.common.core.Result;
import com.platform.common.core.ResultCode;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author guoshao
 * token 相关,重写token过期，登录相关
 */
@Slf4j
@Component
@AllArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

	@Override
	@SneakyThrows
	public void commence(HttpServletRequest request, HttpServletResponse response,
						 AuthenticationException authException) {
		ObjectMapper objectMapper = new ObjectMapper();
		response.setCharacterEncoding("UTF-8");
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		Result result = new Result();
		result.setCode(ResultCode.WEB_400.code());
		if (authException != null) {
			result.setMsg(authException.getMessage());
			result.setData(authException.getMessage());

			if(authException instanceof BadCredentialsException){
				result.setMsg("用户名或密码错误");
				result.setData("Incorrect username or password");
			}else if(authException instanceof InsufficientAuthenticationException
					|| authException instanceof CredentialsExpiredException){
				result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
				result.setMsg("证书过期请重新登录");
				result.setData("invalid_token");
			}

		}
		response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(objectMapper.writeValueAsString(result));
	}
}
